#include <iostream>
#include "Protocol.hpp"
#include "NetCalculatec.hpp"
#include "Listener.hpp"
#include "Reactor.hpp"

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        LogModule::LOG(FATAL) << "参数错误，请正确传参";
        exit(USAGE_ERR);
    }
    uint16_t port = std::stoi(argv[1]);

    std::shared_ptr<NetCalculate> cal = std::make_shared<NetCalculate>();
    std::shared_ptr<Protocol> protocol = std::make_shared<Protocol>([&cal](Request &req) -> Response
                                                                    { return cal->Execute(req); });

    std::shared_ptr<Connection> conn = std::make_shared<Listener>(port);
    conn->SetHandleRegeister([&protocol](std::string &Message) -> std::string
                             {
        LogModule::LOG(DEBUG) << "进入到匿名函数中...";
        std::string response_str;
        while (true)
        {
            std::string package;
            if (!protocol->ReleaseEncauplationMessage(Message, &package))
                break;
            // 我敢保证，我的packge一定是一个完整的请求，是字节流的
            response_str += protocol->GetRequest(package);
        }
        LogModule::LOG(DEBUG) << "结束匿名函数中...: " << response_str;
        return response_str; });

    std::unique_ptr<Reactor> ssptr = std::make_unique<Reactor>();
    ssptr->AddConnection(conn);
    ssptr->Loop();

    return 0;
}